#include <cstdlib>
#include <fstream>
#include <iostream>
#include <json/json.h>
#include <json/value.h>
#include <json/writer.h>
#include <ostream>
#include <streambuf>
#include <vector>

using namespace std;

void json_write(std::string path)
{
    Json::Value root;
    root["name"] = "张三";
    root["age"]  = 18;

    Json::Value scores;
    scores.append(89.5);
    scores.append(90.0);
    scores.append(67.5);
    root["score"] = scores;

    Json::FastWriter writer;
    string           json = writer.write(root);

    // 写入文件
    ofstream file(path);
    if (!file.is_open()) {
        std::cout << "文件打开失败" << std::endl;
        exit(EXIT_FAILURE);
    }
    file.write(json.c_str(), json.length());
    file.close();
}

void json_read(std::string path)
{
    Json::Reader reader;
    Json::Value  root;

    ifstream file(path);
    if (!file.is_open()) {
        std::cout << "文件读取失败" << std::endl;
        exit(EXIT_FAILURE);
    }

    stringstream sstream;
    sstream << file.rdbuf();
    file.close();

    if (!reader.parse(sstream.str(), root)) {
        std::cout << "json 解析失败" << std::endl;
        exit(EXIT_FAILURE);
    }

    if (root.isMember("name")) {
        string name = root["name"].asString();
        std::cout << "name  : " << name << std::endl;
    }

    if (root["age"].isInt()) {
        int age = root["age"].asInt();
        std::cout << "age   : " << age << std::endl;
    }

    Json::Value scores = root["score"];
    for (Json::ValueIterator v = scores.begin(); v != scores.end(); v++) {
        std::cout << "scores: " << v->asDouble() << std::endl;
    }
}

int main(int argc, char *argv[])
{
    json_write("jsoncpp.json");
    json_read("jsoncpp.json");
    return 0;
}